﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using YougeBookmark.Models;

namespace YougeBookmark.DataAccess;

/// <summary>
/// 数据库上下文类
/// </summary>
public class AppDbContext : DbContext
{

    // 添加构造函数，接收 DbContextOptions<AppDbContext>
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public AppDbContext() { }

    // 实体集合
    public DbSet<Bookmark> Bookmarks { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // 从配置文件读取连接字符串
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        options.UseSqlite(configuration.GetConnectionString("SQLite"));
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 标签名称唯一约束
        modelBuilder.Entity<Tag>()
            .HasIndex(t => t.Name)
            .IsUnique();
    }
}